<template>
  <basic-container>
    <el-container>
      <el-aside width="200px">
        <avue-tree :option="treeOption" :data="treeData" @node-click="treeNodeClick">
        </avue-tree>
      </el-aside>
      <el-main>
          <avue-crud :option="option"
                  :table-loading="loading"
                  :data="data"
                  ref="crud"
                  v-model="form"
                  :defaults.sync="showColumn"
                  :permission="permissionList"
                  :page.sync="page"
                  :before-open="beforeOpen"
                  @sortable-change="sortableChange"
                  @row-del="rowDel"
                  @row-update="rowUpdate"
                  @row-save="rowSave"
                  @refresh-change="refreshChange"
                  @search-change="searchChange"
                  @search-reset="searchReset"
                  @selection-change="selectionChange"
                  @current-change="currentChange"
                  @size-change="sizeChange"
                  @filter="filterChange"
                  @sort-change="sortChange"
                  @on-load="onLoad">
          <template slot-scope="scope" slot="menuLeft">
            <el-button type="primary"
                      size="small"
                      icon="el-icon-plus"
                      @click.stop="handleBatchAddUser">提交
            </el-button>
          </template>
        </avue-crud>
      </el-main>
    </el-container> 
  </basic-container>
</template>

<script>
import {queryGeneralOrgInfoListPage} from '@/api/general/staff/generalOrgInfoApi';
import {exportGeneralStaffInfoExcel,saveOrUpdateGeneralStaffInfo,saveOrUpdateGeneralStaffInfoList,saveGeneralStaffInfo,saveGeneralStaffInfoList,deleteGeneralStaffInfo,queryGeneralStaffInfo,queryGeneralStaffInfoListPage,updateGeneralStaffInfo,deleteGeneralStaffInfoList} from '@/api/general/staff/generalStaffInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
export default {
  props: {
    hasSelectIds: {
      type: Object,
      default: ''
    }
  },
  data() {
    return {
      //角色对话框
      fullscreenLoading: false,

      currentRow: {},
      importDataArea: '',
      batchAddDialog: false,
      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        cancelBtn: false,
        printBtn:false,
        saveBtn: false,
        filterBtn:true,  
        menu: false,        
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        reserveSelection:true,
        column: [
          {
            label: 'ID',
            prop: 'id', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '员工用户名',
            prop: 'staffId', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '员工姓名',
            prop: 'staffName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '员工类型',
            prop: 'staffType', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            value:'1',
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[
              {
                label:'自有员工',
                value:'1'
              },{
                label:'借调人员',
                value:'2'
              },
              {
                label:'外包人员',
                value:'3'
              }
            ]
          },
          {
            label: '公司名称',
            prop: 'companyName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '手机号码',
            prop: 'mobileNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '邮箱',
            prop: 'emailAddress', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '状态',
            prop: 'staffStatus', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
        ]
      },
      data: [],
      // 组织机构树形区
      checkedNode: '',
      currentOrgNo: '',
      orgType: '1',
      treeData:[],
      treeOption:{
        addBtn: false,
        menu: false,
        defaultExpandAll:false,
        formOption:{},
        lazy: true,
        treeLoad: (node, resolve) => {
          this.singleBody = {
            parentOrgNo: node.data.orgNo
          } 
          if (node.level === 0) {
            this.singleBody = {
              parentOrgNo: this.website.orgNo.genTreeOrgNo,
              orgType:this.orgType
            }
          }
          this.reqParams =  { 
            singleBody: this.singleBody,
            listBody: [],  
            extBody: {},  
            sqlCondition: [],  
            orderRule: [{prop:'order_seq',order:'ascending'}],
            currentPage: 0,
            pageSize: 99999,
            total: 100 
          }
          this.commonData = reqCommonMsg(this.reqParams)
          queryGeneralOrgInfoListPage(this.commonData).then(res => {
            let data = res.data.body.listBody;
            data.forEach(element => {
              if(!element.hasChildren){
                element.leaf = true
              }
            });
            return resolve(data)
          }, error => {});
        },
        props: {
          label: 'orgName',
          value: 'orgNo'
        },
      },
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.sys_user_org_add, false),
        viewBtn: this.vaildData(this.permission.sys_user_org_view, false),
        delBtn: this.vaildData(this.permission.sys_user_org_delete, false),
        editBtn: this.vaildData(this.permission.sys_user_org_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 批量新增记录,调用父组件方法
     */
    handleBatchAddUser(){
      this.$confirm('确定要添加用户?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$emit('handleBatchAdd', this.selectionList)
          this.selectionList = null;
        }).catch(() => {});
    },
    /**
     * 机构树形菜单点击时触发事件
     */
    treeNodeClick(data){
      this.currentOrgNo =  data.orgNo;
      this.onLoad(this.page)
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.singleBody.belongOrgNo=this.currentOrgNo 
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralStaffInfoListPage(this.commonData).then(res => {
        
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
        this.selectionList = [];
        if(this.hasSelectIds){
          this.data.forEach(element => {
            if(this.hasSelectIds.indexOf(element.id) >= 0){
              this.selectionList.push(element)
            }
          }); 
        }else{
          this.selectionList = [];
        }
        this.$refs.crud.toggleSelection(this.selectionList);
        this.$emit('getDialogStaffList', data.listBody)
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      this.reqParams.singleBody = row;
      this.reqParams.singleBody.belongOrgName=row.$belongOrgNo;
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralStaffInfo(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralStaffInfo(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralStaffInfo(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
   
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralStaffInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        queryGeneralStaffInfo(commonData).then(res => {
          this.form = res.data.body.singleBody;
        });
      }
      else if (['add'].includes(type)) { 
        this.form = { belongOrgNo : this.currentOrgNo}
      }
      //注意：不能放在mounted里，或出现加载不成功
      this.getOrgTree();
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportGeneralStaffInfoExcel(this.commonData);
    },
    /**
     * 获取树形菜单
     */
    getOrgTree(){
      const column = this.findObject(this.option.column, 'belongOrgNo');
      this.orgTree.forEach((element,index) => {
        if(element.orgType == '1'){
          //this.$console.log('element == ',element);
          column.dicData = [element];
        }
      });
    },
  },
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'generalStaffInfoColumn'});
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'generalStaffInfoColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'generalStaffInfoColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
.el-main {
    margin-left: 5px !important;  
    border-left: 10px solid #f3f3f3 !important;  
}
</style>
